var util = require('../../utils/util.js');  
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['不限', '1 人', '2 人', '3 人', '4 人', '5 人', '6 人'],
    index: 0,
    date: "",
    start_date:"",
    end_date:"",
    time: '12:01',
    send_image: "",
    
    voice_button_msg:"按住 说话",
    recording : "正在 录音",
    record_status : 0,
    recording_image : "",
    
    description : "",
    description_voice: "",
    desc_count: 0,
    description_type: 1,  // 拼单描述类型 1-文字，2-语音
    upload_images: [],

    form_id : 0,

    j: 1,//帧动画初始图片  
    isSpeaking: false,//是否正在说话  
    voices: [],//音频数组  
    imagePath: '',
    toPlay: '',
    isPlay: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // 设置全局图片路径
    this.setData({
      imagePath: app.globalData.imagePath,
      send_image: app.globalData.imagePath + '/send_voice.png',
      recording_image: app.globalData.imagePath + "/luyin_point.png",
    });
    
    var that = this;
    this.recorderManager = wx.getRecorderManager();

    this.recorderManager.onStart(function () {
      speaking.call(that);
      recordImageflash.call(that);
      that.setData({
        isSpeaking: true,
        voice_button_msg: "松开 结束",
        record_status: 1
      })
    });

    this.recorderManager.onError(function () {
      app.checkAuthRecord();
      that.tip("录音失败！", "none");
    });

    this.recorderManager.onStop(function (res) {
      that.setData({
        description_voice: res.tempFilePath,
        record_status: 2
      })
      that.tip("录音完成！")
    });

    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      that.tip("播放录音失败！", "none");
    });

    // 播放结束时触发
    this.innerAudioContext.onStop((res) => {
      
    });

    // 音频自然播放结束事件
    this.innerAudioContext.onEnded((res) => {
      that.setData({
        toPlay: '',
        isPlay: false
      });
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.position) {
      this.setData({
        position: app.globalData.position,
      });
    } else if (this.data.canIUse) {
      app.positionReadyCallback = position => {
        this.setData({
          position: position
        })
      }
    };

    var date = util.formatDate(new Date());
    var time = util.formatTime(new Date());
    var now = new Date();
    now.setDate(now.getDate() + 5);
    var end_date = util.formatDate(now);

    this.setData({
      date: date,
      start_date: date,
      end_date: end_date,
      time: time
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 如果正在播放，跳转页面是停止播放
    if (this.data.isPlay) {
      this.innerAudioContext.stop();

      this.setData({
        toPlay: ''
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  /**
   * 打开地图选择位置
   */
  toMap: function () {
    wx.chooseLocation({
      success: res => {
        app.globalData.latitude = res.latitude;
        app.globalData.longitude = res.longitude;
        app.globalData.position = res.name;
        this.setData({
          position: res.name
        })
      },
      fail: res => {
        app.reportError(res.errMsg, 'toAction-toMap-wx.chooseLocation');
        app.checkAuthUserLocation();
      }
    })
  },
  /**
   * 切换描述方式
   */
  changeSendMethod: function(e) {
    app.checkAuthRecord();

    var change_image = app.globalData.imagePath + "/send_character.png";
    if (this.data.description_type == 2) {
      change_image = app.globalData.imagePath + "/send_voice.png";
      this.data.description_type = 1;
    } else {
      this.data.description_type = 2;
    }

    this.setData({
      send_image: change_image,
      description_type: this.data.description_type
    });
  },
  bindUserNumberChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },
  /**
   * 日期修改赋值
   */
  bindDateChange : function(e) {
    this.setData({
      date: e.detail.value
    })
  },
  /**
   * 结束时间修改赋值
   */
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  }
  /**
   * 拼单描述确认字数
   */
  ,descConfirm : function(e) {
    var desc_length = 60;
    var desc = e.detail.value;
    if (desc.length > desc_length) {
      desc = desc.substring(0, desc_length);
      this.setData({
        description: desc,
      });
    }
    this.setData({
      desc_count: desc.length,
      description: e.detail.value
    });
  },
  /**
   * 图片上传
   * */
  uploadImage: function() {
    var count = 9 - this.data.upload_images.length;
    wx.chooseImage({
      count: count,                             // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],      // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        var upload_images = this.data.upload_images;
        for (var i=0; i<tempFilePaths.length; i++) {
          upload_images.push(tempFilePaths[i]);
        }
        
        this.setData({
          upload_images: upload_images
        });

      }
    })
  }
  /**
   * 创建拼单
   */
  , formSubmit: function(e) {

    var formId = e.detail.formId;
    var that = this;
    // 判断描述不能为空
    if ('' == that.data.description_voice && '' == that.data.description) {
      wx.showToast({
        title: '请填写拼单文字或语音！',
        icon: 'none',
        duration: 1500
      });
      return false;
    }

    wx.showToast({
      icon: "loading",
      title: "正在上传"
    });

    var order_id = 0;
    const requestTask = wx.request({
      url: app.globalData.apiUrl + 'order/addOrder', //仅为示例，并非真实的接口地址
      method : 'POST',
      data: {
        usernumber: that.data.index,
        end_datetime: that.data.date+' '+that.data.time,
        description: that.data.description,
        description_type: that.data.description_type,
        latitude: app.globalData.latitude,
        longitude: app.globalData.longitude,
        position:app.globalData.position,
        form_id: formId
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      success: function (res) {
        
        if (res.data.code > 10000) {
          wx.showToast({
            title: '提交失败，请重试！',
            icon: 'none'
          });
        } else {
          order_id = res.data.message;
          
          // 将录音文件合并到图片数组中统一上传
          if (that.data.description_voice != '') {
            var i = that.data.upload_images.length;
            that.data.upload_images[i] = that.data.description_voice;
          }

          var images = that.data.upload_images;
          var images_length = images.length;
          if (images_length <= 0) {
            wx.showToast({
              title: '提交成功！',
              icon: 'success',
              duration: 2000,
              complete: function () {
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/detail/detail?id=' + order_id,
                  });
                }, 2000);
              }
            });
            return true;
          }

          for (var i = 0; i < images_length; i++) {
            wx.uploadFile({
              url: app.globalData.apiUrl + 'order/uploadImageVoice', //仅为示例，非真实的接口地址
              header: {
                'content-type': 'multipart/form-data',
                'Cookie': 'PHPSESSID=' + wx.getStorageSync('sessionID')
              },
              filePath: encodeURI(images[i]),
              name: 'file',
              formData: {
                'order_id': encodeURI(order_id)
              },
              success: function (res) {
                wx.showToast({
                  title: '提交成功！',
                  icon: 'success',
                  duration: 2000,
                  complete: function () {
                    setTimeout(function(){
                      wx.redirectTo({
                        url: '/pages/detail/detail?id=' + order_id,
                      });
                    }, 2000);
                  }
                });
              },
              fail: function (res) {

                app.reportError(res.errMsg, 'toAction-formSubmit-order/uploadImageVoice');

                wx.showModal({
                  title: '提示',
                  content: '图片上传失败！',
                  showCancel: false,
                  success: function() {
                    wx.switchTab({
                      url: '/pages/index/index'
                    })
                  }
                });
              }
            });
          }
        }
      },
      fail:function(res) {

        app.reportError(res.errMsg, 'toAction-formSubmit-order/addOrder');

        wx.showToast({
          title: '提交失败，请重试！',
          icon: 'none',
          duration: 2000
        });
      }
    })
  }
  /**
  * 提示
  */
  , tip: function (msg, status = 'success') {
    wx.showToast({
      title: msg,
      icon: status,
      duration: 1000
    });
  }

  /**
   * 录制aac音频
   */
  , startRecordAac: function () {
    this.recorderManager.start({
      format: 'aac'
    });
  }

  /**
   * 录制mp3音频
  */
  , startRecordMp3: function () {
    this.recorderManager.start({
      format: 'mp3'
    });
  }

  /**
   * 停止录音
   */
  , stopRecord: function () {

    this.setData({
      toPlay: '',
      isPlay: false
    });

    this.recorderManager.stop();
  }

  /**
   * 播放录音
   */
  , playRecord: function () {
    var that = this;
    var description_voice = this.data.description_voice;
    if (description_voice == '') {
      this.tip("请先录音！")
      return;
    }
    this.innerAudioContext.src = this.data.description_voice;
    this.innerAudioContext.play()

    this.setData({
      toPlay: description_voice,
      isPlay: true
    });
  }
  /**
   * 暂停播放
   */
  , stopPlayRecord: function () {

    this.innerAudioContext.stop();

    this.setData({
      toPlay: '',
      isPlay: false
    });
  }
  /**
   * 删除录音
   */
  , deleteRecord : function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除录音吗？',
      success: function (res) {
        if (res.confirm) {
          that.data.description_voice = '';
          that.setData({
            description_voice : ''
          });
        } 
      }
    });
  }
   /**
   * 图片展示
   */
  , showImage: function (e) {
    var id = e.currentTarget.id;
    if (this.data.upload_images.length > 0 && this.data.upload_images[id] != '') {
      var urls = [];

      for (var i = 0; i < this.data.upload_images.length; i++) {
        urls[i] = this.data.upload_images[i];
      }

      var currentImageUrl = this.data.upload_images[id];
      wx.previewImage({
        current: currentImageUrl, // 当前显示图片的http链接
        urls: urls // 需要预览的图片http链接列表
      });
    }
  }
  /**
   * 删除图片
   */
  , deleteImage : function(e) {

    var id = e.currentTarget.id;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          that.data.upload_images.splice(id, 1);
          that.setData({
            upload_images: that.data.upload_images
          });
        }
      }
    });
  }
  /**
   * To Home Page
   */
  , toHome: function (e) {
    app.formIdSubmit(e);
    wx.switchTab({
      url: '/pages/index/index',
    });
  }
  /**
   * To My Page
   */
  , toMy: function (e) {
    app.formIdSubmit(e);
    wx.switchTab({
      url: '/pages/center/center',
    });
  }
})

// 录音展示图片动态闪烁
function recordImageflash() {
  var _this = this;
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 2;
    var image_patch = "";
    if (i == 0) {
      image_patch = app.globalData.imagePath + "/luyin_point.png";
    }
    _this.setData({
      recording_image: image_patch,
    })
  }, 600);
}

//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}

var t = Date.now();
function sleep(d) {
  while (Date.now - t <= d);
}
